package cn.wolfcode.shop.cloud.mq;


import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.util.SeckillGoodsCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_TAG
)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("进入到订单创建队列");
        Long seckillId = orderMessage.getSeckillId();
        Long userId = orderMessage.getUserId();
        String uuid = orderMessage.getUuid();
        Map<String,Object> data = new HashMap<>();
        data.put("seckillId", seckillId);
        data.put("userId", userId);
        data.put("uuid", uuid);
        //int i = 1/0;
        try {
            String orderNo = orderInfoService.seckill(seckillId, userId);
            //成功以后通知用户
            data.put("code", 200);
            data.put("data", orderNo);
            rocketMQTemplate.syncSend(MQConstans.CREATE_SUCCESS_DEST, data);
        } catch(Exception e) {
            //失败也通知
            data.put("code", SeckillGoodsCodeMsg.SECKILL_FAIL.getCode());
            data.put("msg", SeckillGoodsCodeMsg.SECKILL_FAIL.getMsg());
            rocketMQTemplate.syncSend(MQConstans.CREATE_FAIL_DEST,data);
        }
    }
}
